import {isLogin, httpGetResponse} from '@/utils/ajax'
import {dotData} from '@/utils'
import localStore from 'store'

const menu = {
  state: {
    list: [],
    listMap: {},
    init: false
  },

  mutations: {
    SET_MENU_LIST: (state, list) => {
      state.list = list
      // 设置一个Map 方便获取
      state.listMap = list.reduce((total, item) => {
        if (Array.isArray(total[item.path])) {
          total[item.path].push(item)
        } else {
          total[item.path] = [item]
        }
        return total
      }, {})
      state.init = true
    }
  },

  actions: {
    INIT_MENU_LIST({commit, state}, data) {
      return new Promise((resolve, reject) => {
        if (isLogin() && !state.init) {
          // 如果是开发环境
          let p
          if (localStore.get('dev')) {
            p = import('@/utils/menuData').then(menuData => {
              return {success: true, data: menuData.default}
            })
          } else {
            p = httpGetResponse('/ms-common-user/menu/menu-user-id', {projectType: process.env.projectType})
          }
          p.then(response => {
            const success = dotData(response, 'success')
            if (success) {
              let data = dotData(response, 'data')
              if (Array.isArray(data)) {
                commit('SET_MENU_LIST', data.map(v => {
                  return {
                    path: v.path, // 路径
                    id: v.id, // id
                    pid: v.pid, // 父id
                    text: v.text, // 文本
                    hidden: parseInt(v.hidden) || 0,
                    icon: v.icon
                  }
                }))
              }
            }
          }).then(_ => {
            resolve()
          }).catch(e => {
            reject(e)
          })
        } else {
          reject(new Error('未登陆'))
        }
      })
    }
  }
}

export default menu
